<script setup lang="ts">
import { ref, unref, watchEffect, nextTick } from 'vue'
import { SettingOutlined, DragOutlined } from '@ant-design/icons-vue'
import { useI18n } from '@/locales/useI18n'
import { isBoolean } from '@/utils/is'
import { BasicTableColumn } from '../../typing'
import Sortablejs from 'sortablejs'
import type Sortable from 'sortablejs'

const { t } = useI18n()
const emit = defineEmits([
  'update:indexChecked',
  'update:selectChecked',
  'reset'
])

const props = defineProps({
  indexChecked: Boolean,
  selectChecked: Boolean,
  sortColumns: { type: Array<BasicTableColumn>, required: true },
  iconSize: { type: Number, default: 20 }
})

const indexChecked = ref(false)
const selectChecked = ref(false)
const columnsCheckedSource = {
  indexChecked: isBoolean(props.indexChecked)
    ? props.indexChecked
    : indexChecked.value,
  selectChecked: isBoolean(props.selectChecked)
    ? props.selectChecked
    : selectChecked.value
}

const initData = () => {
  indexChecked.value = columnsCheckedSource.indexChecked
  selectChecked.value = columnsCheckedSource.selectChecked
}

watchEffect(() => {
  initData()
})

const sortInstance = ref()
const sortable = ref<Sortable>()
let sortableOrder: string[] = []
let sortInited = false

const handleSettingPopoverChange = () => {
  if (sortInited) return
  nextTick(() => {
    const columnListEl = unref(sortInstance)
    if (!columnListEl) return
    const el = columnListEl.$el as any
    if (!el) return

    sortable.value = new Sortablejs(el, {
      animation: 500,
      delay: 400,
      delayOnTouchOnly: true,
      ghostClass: 'blue-background-class',
      handle: '.table-column-drag-icon ',
      onEnd: ({ oldIndex, newIndex }) => {
        let old = oldIndex as number
        let now = newIndex as number
        const source = props['sortColumns'][old]
        const destination = props['sortColumns'][now]
        props['sortColumns'][now] = source
        props['sortColumns'][old] = destination
      }
    })
    sortableOrder = sortable.value.toArray()
    sortInited = true
  })
}

const onReset = () => {
  sortable.value?.sort(sortableOrder)
  initData()
  emit('update:indexChecked', indexChecked.value)
  emit('update:selectChecked', selectChecked.value)
  emit('reset')
}
</script>

<template>
  <a-tooltip>
    <template #title> {{ t('component.table.settingColumn') }} </template>
    <a-popover
      trigger="click"
      placement="bottomRight"
      overlayClassName="system-basic-column-setting__cloumn-list"
      :get-popup-container="(node: any) => node.parentNode"
      arrow-point-at-center
      @visible-change="handleSettingPopoverChange"
    >
      <setting-outlined :style="{ fontSize: iconSize + 'px' }" />
      <template #title>
        <a-row justify="space-between">
          <a-col>
            <a-checkbox
              v-model:checked="indexChecked"
              @change="$emit('update:indexChecked', indexChecked)"
              >{{ t('system.list.indexColumn') }}</a-checkbox
            >
            <a-checkbox
              v-model:checked="selectChecked"
              @change="$emit('update:selectChecked', selectChecked)"
              >{{ t('system.list.selectColumn') }}</a-checkbox
            >
          </a-col>
          <a-col>
            <a type="link" class="columns-reset-btn" @click="onReset">{{
              t('system.reset')
            }}</a>
          </a-col>
        </a-row>
      </template>
      <template #content>
        <div id="sortable" ref="sortInstance">
          <a-space direction="vertical" style="width: 100%">
            <a-row
              justify="space-between"
              v-for="item in sortColumns"
              :key="item.dataIndex"
            >
              <a-col>
                <a-space>
                  <drag-outlined style="cursor: move" />
                  <a-checkbox v-model:checked="item.checked">{{
                    item.title
                  }}</a-checkbox>
                </a-space>
              </a-col>
            </a-row>
          </a-space>
        </div>
      </template>
    </a-popover>
  </a-tooltip>
</template>